package org.devocean.groupbuying.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.devocean.groupbuying.dao.CategoryDAO;
import org.devocean.groupbuying.domain.CategoriesLocalization;
import org.devocean.groupbuying.domain.Category;
import org.springframework.stereotype.Repository;

@Repository
public class CategoryDAOImpl implements CategoryDAO {

	@PersistenceContext
	private EntityManager em;

	public List<Category> findAllCategorys() {
		return em
				.createQuery(
						"SELECT c  FROM Category c JOIN FETCH  c.categoriesLocalization",
						Category.class).getResultList();
	}

	public void deleteCategory(Integer categoryId) {
		final Category category = em.find(Category.class, categoryId);
		if (category != null) {
			CategoriesLocalization categoriesLocalization = category
					.getCategoriesLocalization();
			if (categoriesLocalization.getArticlesLocalizations().size() == 0
					&& categoriesLocalization.getMedia().size() == 0) {
				if (categoriesLocalization.getCategories().size() > 1) {
					categoriesLocalization.getCategories().remove(category);
					em.remove(category);
				} else {
					em.remove(categoriesLocalization);
				}

				em.flush();
			}
		}

	}

	public Category findCategoryById(Integer id) {
		return em.find(Category.class, id);
	}

	public List<Category> findCategoriesById(String criteria, Integer start,
			Integer size) {

		return em
				.createQuery(
						"select c from Category c JOIN FETCH  c.categoriesLocalization where c.name like :criteria",
						Category.class)
				.setParameter("criteria", criteria + "%").setFirstResult(start)
				.setMaxResults(size).getResultList();
	}

	public Long countCategoriesByCriteria(String criteria) {
		return em
				.createQuery(
						"select COUNT(c) from Category c where c.name like :criteria",
						Long.class).setParameter("criteria", criteria + "%")
				.getSingleResult();
	}

	public List<Category> findDisplayCategories(String lang) {
		return (List<Category>) em
				.createQuery(
						"SELECT c from Category c INNER JOIN FETCH c.categoriesLocalization cl WHERE cl.display=1 AND c.lang=:lang",
						Category.class).setParameter("lang", lang)
				.getResultList();

	}
}
